<script setup lang="ts">
import { onMounted, ref } from "vue";
import { useBase64 } from "vue-cache-optimization"; // ./utils vue-cache-optimization
import image from "./../assets/vue.svg";
import { downFile } from "./../utils/useFile";


const newSrc = ref();
const getBase64 = (el: Element, str: string) => {
  console.log("getBase64...", el, str);
  newSrc.value = str;
};

const vBase64current = {
  mounted(el: HTMLImageElement, binding: any) {
    const fn = binding.value;
    if (fn) {
      el.onload = () => {
        fn(el, useBase64(el));
      };
    }
  },
};

const img = ref();
const imgBase64 = ref("");
const getCurrentData = () => {
  console.log("通过 ref 拿到当前 img 元素", img.value);
  imgBase64.value = useBase64(img.value);
  console.log("通过 useBase64 得到元素 base64", imgBase64.value);
};
const downImg = () => {
    downFile(imgBase64.value, "test.png");
};
const clearImg = () => {
  imgBase64.value = "";
};

onMounted(() => {
  // console.log('mounted', image)
});
</script>

<template>
  <div>
    <p>TestBase64</p>
    <h2>测试全局指令 v-base64</h2>
    <p>
      <span>引入图片:</span>
      <img :src="image" v-base64="getBase64" alt="" />
      <span>通过 v-base64 拿到数据:</span>
    </p>
    <p>
      <textarea v-model="newSrc" id="" cols="100" rows="10"></textarea>
    </p>
    <p>
      <span>用 base64 数据展示图片:</span>
      <img :src="newSrc" alt="" />
    </p>
    <h2>测试组件内指令 v-base64current</h2>
    <p>
      <img :src="image" v-base64current="getBase64" alt="" />
    </p>
    <h2>测试 useBase64 函数</h2>
    <p>
      <img ref="img" :src="image" />
      <button @click="getCurrentData()">获取当前图片的 base64</button>
      <button v-show="imgBase64" @click="downImg()">下载 base64 图片</button>
      <button @click="clearImg()">清除数据</button>
    </p>
    <p>
      <textarea v-model="imgBase64" id="" cols="100" rows="10"></textarea>
    </p>
  </div>
</template>

<style>
.images img {
  width: 200px;
  opacity: 0.2;
}
</style>
